package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Resource
    MongoTemplate mongoTemplate;
    @Resource
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
//        1. 校验参数 文章id必须传
        if (dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
//        2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
//        ApBehaviorEntry apBehaviorEntry =
//                apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId
                (user==null?null:user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "获取行为实体信息失败");
        }
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).
                and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
//        3. 判断阅读行为是否存在
//        4. 存在  将阅读行为的count字段加1 并修改
//        5. 不存在  创建阅读行为 并初始化count字段值为 1
        if (readBehavior == null) {
            readBehavior = new ApReadBehavior();
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount((short) 1);
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setCreatedTime(new Date());
            readBehavior.setEntryId(apBehaviorEntry.getId());
            mongoTemplate.save(readBehavior);
        }else {
            readBehavior.setCount((short) (readBehavior.getCount()+1));
//            Update update=new Update();
//            update.set("count",readBehavior.getCount()+1);
//            mongoTemplate.updateMulti(query,update,ApReadBehavior.class);
            mongoTemplate.save(readBehavior);
        }
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setAdd(1);
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));

        log.info("阅读行为 发送消息 ==>{}",JSON.toJSONString(mess));
        return ResponseResult.okResult();
    }


}
